<template>
  <Dialog v-model="dialogVisible" :title="t('judgeScene.initial.suggestList')" width="1200">
    <ContentWrap>
      <!-- // 评选状态(judgeStatus) 1=未开始 2=初评进行中 3=初评结束 4=终评进行中 5=终评结束 -->
      <template v-if="!isFinal">
        <el-button
          type="success"
          @click="handleConfirmResult"
          :disabled="awardsInfo.judgeStatus !== 2"
        >
          <Icon icon="ep:check" class="mr-5px" />
          {{ t('judgeScene.initial.confirmResult') }}
        </el-button>
      </template>
      <template v-if="isFinal">
        <el-button
          type="success"
          @click="handleConfirmResult"
          :disabled="awardsInfo.judgeStatus !== 4"
        >
          <Icon icon="ep:check" class="mr-5px" />
          {{ t('judgeScene.final.confirmResult') }}
        </el-button>
      </template>
    </ContentWrap>
    <vxe-table
      id="iJudgeResultForm-table"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('candidate.fields.jobCode')"
        field="jobCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.major')"
        field="major"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('judgeScene.initial.awardLevel')"
        field="awardLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <!-- 通用奖 -->
      <template v-if="isCommon">
        <!-- 通用初评 -->
        <template v-if="!isFinal">
          <!-- 本轮成绩 -->
          <vxe-column
            :title="t('judgeScene.newResult.roundScore')"
            field="value"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <!-- 是否终评 -->
          <vxe-column
            :title="t('judgeScene.newResult.isNext')"
            field="isNext"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isNext">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
          <!-- 是否平票 -->
          <vxe-column
            :title="t('judgeScene.newResult.isCoordinate')"
            field="isCoordinate"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isCoordinate">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
        </template>
        <!-- 通用终评 -->
        <template v-if="isFinal">
          <!-- 初评成绩 -->
          <vxe-column
            :title="t('judgeScene.newResult.initialScore')"
            field="initialScore"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <!-- 本轮成绩 -->
          <vxe-column
            :title="t('judgeScene.newResult.roundScore')"
            field="value"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <!-- 是否平票 -->
          <vxe-column
            :title="t('judgeScene.newResult.isCoordinate')"
            field="isCoordinate"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isCoordinate">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
          <!-- 是否获奖 -->
          <vxe-column
            :title="t('judgeScene.newResult.isWin')"
            field="isWin"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isWin">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
        </template>
      </template>
      <!-- 师昌绪 -->
      <template v-if="!isCommon">
        <!-- 师昌绪初评 -->
        <template v-if="!isFinal">
          <!-- 保持原样 -->
          <vxe-column
            :title="t('judgeScene.initial.initialScore')"
            field="initialScore"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <vxe-column
            :title="t('judgeScene.initial.suggestLevel')"
            field="value"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <vxe-column
            :title="t('judgeScene.initial.adminConfirm')"
            field="adminConfirm"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.adminConfirm">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
          <vxe-column
            :title="t('judgeScene.initial.isNext')"
            field="isNext"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isNext">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
          <vxe-column
            :title="t('judgeScene.initial.isCoordinate')"
            field="isCoordinate"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isCoordinate">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
        </template>
        <!-- 师昌绪终评 -->
        <template v-if="isFinal">
          <!-- 初评成绩 -->
          <vxe-column
            :title="t('judgeScene.newResult.initialScore')"
            field="initialScore"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <!-- 本轮成绩 -->
          <vxe-column
            :title="t('judgeScene.newResult.roundScore')"
            field="value"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          />
          <!-- 是否平票 -->
          <vxe-column
            :title="t('judgeScene.newResult.isCoordinate')"
            field="isCoordinate"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isCoordinate">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
          <!-- 是否获奖 -->
          <vxe-column
            :title="t('judgeScene.newResult.isWin')"
            field="isWin"
            align="center"
            show-header-overflow
            show-overflow
            min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.isWin">{{ t('common.yes') }}</span>
              <span v-else>{{ t('common.no') }}</span>
            </template>
          </vxe-column>
        </template>
      </template>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleViewResultDetail(scope.row)">
            {{ t('judgeScene.initial.resultDetail') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </Dialog>
  <CandidateResultDetail ref="candidateResultDetailFormRef" />
</template>

<script setup lang="ts">
import { ReviewSceneApi, StudentAwardResultResVO } from '@/api/awards/reviewscene'
import type { VxeTablePropTypes } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import CandidateResultDetail from '@/views/awards/candidate/components/CandidateResultDetail.vue'
import { type RouteLocationNormalizedLoaded, useRouter } from 'vue-router'
import { nextTick, ref, unref } from 'vue'
import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({ name: 'JudgeForm' })

const { currentRoute, push, replace } = useRouter()
const tagsViewStore = useTagsViewStore()

const props = defineProps<{
  stageName: string
}>()

const awardsInfo = inject('awardsInfo')

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const list = ref<StudentAwardResultResVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  awardsInstanceId: undefined,
  roundId: undefined
})

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const isFinal = computed(() => {
  return props.stageName && props.stageName === '终评'
})

const isCommon = computed(() => {
  return awardsInfo.value?.awardsType === 0
})

const getList = async () => {
  loading.value = true
  queryParams.awardsInstanceId = awardsId.value as any
  queryParams.roundId = roundId.value as any
  try {
    const data = await ReviewSceneApi.getStudentAwardResult(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const awardsId = ref('')
const roundId = ref('')
const open = async (_awardsId: string, _roundId: string) => {
  awardsId.value = _awardsId
  roundId.value = _roundId
  resetForm()
  dialogVisible.value = true
  getList()
}

const resetForm = () => {
  list.value = []
  total.value = 0
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  queryParams.awardsInstanceId = undefined
  queryParams.roundId = undefined
}

const emits = defineEmits(['refresh'])

const selectedTag = ref<RouteLocationNormalizedLoaded>()

// 确认结果
const confirmLoading = ref(false)
const handleConfirmResult = async () => {
  try {
    if (!isFinal) {
      await message.confirm(t('judgeScene.initial.confirmResultTips'))
    } else {
      await message.confirm(t('judgeScene.final.confirmResultTips'))
    }
  } catch {
    return
  }
  confirmLoading.value = true
  try {
    await ReviewSceneApi.confirmStudentAwardResult(awardsId.value, roundId.value)
    if (!isFinal) {
      message.success(t('judgeScene.initial.confirmSuccess'))
    } else {
      message.success(t('judgeScene.final.confirmSuccess'))
    }
    dialogVisible.value = false
    emits('refresh')
  } finally {
    confirmLoading.value = false
    selectedTag.value = unref(currentRoute)
    tagsViewStore.delCachedView()
    const { path, query } = selectedTag.value
    await nextTick()
    replace({
      path: '/redirect' + path,
      query: query
    })
  }
}

// 查看推荐明细
const candidateResultDetailFormRef = ref<InstanceType<typeof CandidateResultDetail>>()
const handleViewResultDetail = (row: StudentAwardResultResVO) => {
  candidateResultDetailFormRef.value?.open(
    {
      id: row.awardsCandidateId,
      awardId: row.awardsInstanceId
    } as any,
    roundId.value ?? ''
  )
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
